import random

from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView

from apps.verifications import serializers
from libs.captcha.captcha import captcha
from django import http
from django_redis import get_redis_connection

from libs.yuntongxun.sms import CCP


class ImageCodeView(APIView):

    def get(self,request,image_code_id):
        #1,生成图片验证码
        text,image_data = captcha.generate_captcha()

        data = request.query_params
        pre_id = data['pre_id']
        redis_conn = get_redis_connection("code")

        if pre_id:
            redis_conn.delete('image_code_%s' % pre_id)

        #2,保存图片验证码的值

        redis_conn.setex("image_code_%s"%image_code_id,300,text)

        #3,返回
        response = http.HttpResponse(image_data)
        response["Content-Type"] = "image/png"
        return response

class SmsCodeView(GenericAPIView):
    serializer_class = serializers.SmsCodeSerializer
    def get(self,request,mobile):
        dict_data = request.query_params

        serializer = self.get_serializer(data=dict_data)
        serializer.is_valid(raise_exception=True)

        redis_conn = get_redis_connection('code')
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            return Response(data={'errmsg':'频繁点击'},
                             status=status.HTTP_400_BAD_REQUEST
                             )
        sms_code = '%06d' % random.randint(0,99999)

        print(sms_code)
        # from celery_tasks.sms.tasks import send_sms_code
        # send_sms_code.delay(mobile, sms_code)
        #云通讯
        # result = CCP().send_template_sms(mobile,[sms_code,5],1)
        #
        # if result == 1:
        #     return http.HttpResponseBadRequest('发送失败')

        redis_conn.setex('send_flag_%s' % mobile,60,True)
        redis_conn.setex("sms_code_%s" % mobile , 300 , sms_code)

        return Response(status=status.HTTP_200_OK)

